/**
 * Created by Dalyn on 2017/3/7.
 */
import React from "react";
import { hashHistory } from 'react-router';
import Confirm from "../common/Confirm.js";
import InputBox from "../common/InputBox.js";
import Test from "../common/Test.js";
import Relay from "react-relay";
import SendCodeMutation from "./mutation/SendCodeMutation"
import CodeValidateMutation from "./mutation/CodeValidateMutation"
import ResetUserPwdTwoStepMutation from "./mutation/ResetUserPwdTwoStepMutation"


export default class Find_pw1 extends React.Component{
    constructor(props) {
        super(props);
        this.style={
            username: {
                width: "254px",
                height: "40px",
                borderColor: "#bbbbbb",
                marginTop: "15px"
            },
            next:{
                width: '256px',
                height: '42px',
                backgroundColor:"#1b3249",
                fontSize:"18px",
                color:"#fff",
                marginTop:"16px",
                fontFamily: "Microsoft YaHei"
            },
            v_code:{
                width: "110px",
                height: "40px",
                paddingLeft: '6px',
                border: "1px solid #ededed",
            },
            fetch:{
                width: '103px',
                height: '30px',
                backgroundColor:"#36b3b3",
                borderRadius:"3px",
                fontSize:"14px",
                color:"#fff",
                marginTop:"6px",
                marginLeft:"20px",
                border: '1px solid #ededed',
                fontFamily: "Microsoft YaHei"
            }
        };
        this.code = '';
        this.phone = '';
        this.token = '';
        this.verifycodetoken = ''
        this.state={
            codehint:'',
            remainSecond: '获取验证码',
        }
        this.clockTime= 60;
        this.timer = null;
        this.backtimer = null;
        this.isAlreadyAsked = false

    }
    componentWillMount(){
        this.clearTimer();
        let preAskDate = (new Date()).getTime();
        let senttime = Number(sessionStorage.getItem('senttime'));
        this.code = sessionStorage.getItem('sentcode');
        this.verifycodetoken = sessionStorage.getItem('senttoken');
        let timeerrand = preAskDate-senttime
        let timesecond = Math.floor(timeerrand/1000);
        if(timesecond<60){
            this.clockTime = this.clockTime-timesecond
            this.backtimer = setInterval((()=>{
                this.clockTime = this.clockTime-1
                if(this.clockTime<=0){
                    this.clearTimer();
                }
            }).bind(this),1000);
        }
        let userinfo
        if(this.props.params.token){
            userinfo = this.props.params.token.split('*');
            this.token = userinfo[0];
            this.phone = userinfo[1];
        }
        Relay.Store.commitUpdate(
            new ResetUserPwdTwoStepMutation({
                phone : this.phone,
                token : this.token
            }),
            {
            onFailure:()=>{

            },
            onSuccess:(response)=>{
                let errorCode = response.resetUserPwdOneStep.data.errorCode
                if(errorCode!='0'){
                    hashHistory.push('/')
                }
            }
        });
    }

    componentWillUnmount(){
        this.clearTimer();
    }


    next(){
        let verifycode = this.refs.vcode.state.text;
        if(verifycode==''){
            this.setState({
                codehint:'*验证码不能为空'
            });
            return;
        }
        if(verifycode!=this.code){
            this.setState({
                codehint:'*验证码有误'
            });
            return;
        }
        Relay.Store.commitUpdate(
            new CodeValidateMutation({
                phone:this.phone,
                code:verifycode,
                token:this.verifycodetoken
            }),
            {
                onFailure: () => {
                    conlole.warn('11121212123');
                },
                onSuccess: (response) => {
                    let errorCode = response.codeValidate.codeValidate.errorCode;
                    let value = response.codeValidate.codeValidate.value;
                    if(errorCode =='0'){
                        this.setState({
                            codehint:''
                        });
                        hashHistory.push('/reset_pw1/'+this.verifycodetoken+'*'+this.phone)
                    }else{
                        this.setState({
                            codehint:value
                        });
                    }
                }
            }
        );



    }

    clearTimer() {
        if (this.timer) clearInterval(this.timer);
        if (this.backtimer) clearInterval(this.backtimer);
    }

    beginTimer(){
        this.clearTimer();
        this.refs.getcode.setState({
            disabled:true,
            flag:false
        });
        this.setState({
            remainSecond : this.clockTime
        });
        this.timer = setInterval((()=>{
            // console.warn(this.clockTime);
            this.clockTime = this.clockTime-1;
            this.setState({
                remainSecond: this.state.remainSecond - 1,
            });
            if (this.state.remainSecond <= 0) {
                this.refs.getcode.setState({
                    disabled:false,
                    flag:true
                });
                this.clockTime =60
                this.setState({
                    remainSecond: '获取验证码'
                });
                this.clearTimer();
            }
        }).bind(this),1000);
    }

    touchChange(){
        this.setState({
            codehint:''
        });
        this.beginTimer();
        if(this.clockTime!=60){
            // console.warn('dayu')
        }else{
            // console.warn('xiaoyu')
            // sessionStorage.setItem("senttime", (new Date()).getTime().toString());
            Relay.Store.commitUpdate(
                new SendCodeMutation({
                    phone: this.phone,
                }),
                {
                    onFailure: () => {
                        console.warn('11121212123');
                    },
                    onSuccess: (response) => {
                        let errorCode =  response['sendCode'].sendCode.errorCode
                        let verifycode
                        let token
                        let timeNow
                        if(errorCode=='0'){
                            timeNow = response['sendCode'].sendCode.timeNow;
                            sessionStorage.setItem("senttime", timeNow.toString());
                            verifycode = response['sendCode'].sendCode.code;
                            token = response['sendCode'].sendCode.token
                            this.code = verifycode;
                            this.verifycodetoken = token;
                            console.warn(verifycode);
                            sessionStorage.setItem("sentcode", verifycode.toString());
                            sessionStorage.setItem("senttoken", token.toString());

                        }
                    }
                }
            )
        }

    }


    render(){
        return (
            <div style={Style.box}>
                <p style={Style.p}>找回密码</p>
                <p  style={{"height":"40px",lineHeight:"40px",textAlign:"left",marginTop:"15px",color:'#1b3249', fontSize:'14px'}}>账号：<span>{this.phone}</span></p>
                <div style={{"marginTop":"15px"}} className="clear">
                    <div style={{float:"left"}}>
                        <InputBox style={this.style.v_code} defaultvalute="请输入短信验证码" ref = {'vcode'} maxlength={4} isloginintext={true}/>
                    </div>
                    <div style={{float:"left"}}>
                        <Confirm style={this.style.fetch} tcontext={this.state.remainSecond}
                                 touch={this.touchChange.bind(this)}  ref={'getcode'}/>
                    </div>
                </div>
                <p style={Style.point}>{this.state.codehint}</p>
                <Confirm style={this.style.next} tcontext={'下一步'}
                         touch={this.next.bind(this)}/>
            </div>
        )
    }
}
var Style = {
    box:{
        width:"259px",
        height:"329px",
        margin:"0 auto",
        padding:"10px 0"
    },
    p:{
        height:"18px",
        fontSize:"20px",
        textAlign:"center",
        lineHeight:"18px",
        verticalAlign:"middle",
        padding:"28px 0",
        margin:"0 auto",
        color:"#1b3249",
        fontFamily: "Microsoft YaHei"
    },
    point:{
        width: "256px",
        height: "13px",
        color:"red",
        textAlign: "left",
        lineHeight: "13px",
        padding: "11px 0",
        margin: "0 auto",
        float:'left'
    }
}
